@tool
extends Control

signal tree_update(tree:Dictionary)

const ADD_ICON = preload("res://addons/gameplay-ability-system/assets/Add.svg")
const REMOVE_ICON = preload("res://addons/gameplay-ability-system/assets/Remove.svg")

var ui_tree := Tree.new()
var source_tree:Dictionary = {}

func _ready() -> void:
	
	ui_tree.scroll_horizontal_enabled = false
	ui_tree.scroll_vertical_enabled = false
	ui_tree.button_clicked.connect(_on_tree_button_pressed)
	ui_tree.item_edited.connect(_on_item_edited)
	add_child(ui_tree)
	
	var root = add_tag_tree_item()
	root.set_text(0,"Root")
	root.set_editable(0,false)
	draw_tree(root,source_tree)
	
	update_tree()


func _on_item_edited():
	update_tree()


func _on_tree_button_pressed(item: TreeItem, column: int, id: int, mouse_button_index: int):
	if not id:
		var new_item = add_tag_tree_item(item)
		new_item.set_text(0,item.get_text(0)+".")
	else:
		item.free()
	
	update_tree()


# 递归解析Tree的内容，以字典形式返回root下的所有标签
func parse_tree(root:TreeItem) -> Dictionary:
	var list:Dictionary = {}
	
	for item in root.get_children():
		list[item.get_text(0)] = parse_tree(item)
	
	return list

# 用字典在root下递归绘制Tag树
func draw_tree(root:TreeItem,tree:Dictionary):
	
	for item in tree:
		var child = add_tag_tree_item(root,item)
		draw_tree(child,tree[item])


# 封装添加子项的方法
func add_tag_tree_item(father:TreeItem = null,text:String = "",editable:bool = true) -> TreeItem:
	var tree_item = ui_tree.create_item(father)
	tree_item.set_text(0,text)
	tree_item.set_editable(0,true)
	tree_item.add_button(0,ADD_ICON)
	tree_item.add_button(0,REMOVE_ICON)
	
	return tree_item


func update_tree():
	var root = ui_tree.get_root()
	
	source_tree = parse_tree(root)
	tree_update.emit(source_tree)
	
	# 偏方刷新检查器
	remove_child(ui_tree)
	add_child(ui_tree)
	
